<template>
  <div>
    <a-card :bordered="false" style="margin-top: 24px; min-height: 45vh">
      <a-tabs :default-active-key="defaultKey" @change="tabChange">
        <a-tab-pane key="0" tab="人员管理">
          <div class="table-page-search-wrapper">
            <a-form layout="inline" @keyup.enter.native="onSearch()">
              <a-row :gutter="24">
                <a-col :md="8" :sm="24">
                  <a-form-item label="角色">
                    <a-select v-model="queryParamUser.roleList" placeholder="多选" show-search mode="multiple">
                      <a-select-option v-for="(item, index) in selectRoleList" :key="index" :value="item.id">{{ item.name }}</a-select-option>
                    </a-select>
                  </a-form-item>
                </a-col>
                <a-col :md="8" :sm="24">
                  <a-form-item style="display: flex">
                    <div style="display: flex">
                      <a-select v-model="queryParamUser.searchType" placeholder="请选择" style="width: 130px">
                        <a-select-option v-for="(item, index) in searchTypeList" :key="index" :value="item.type">{{ item.name }}</a-select-option>
                      </a-select>
                      <a-input v-model="queryParamUser.searchValue" placeholder="请输入" style="margin-left: 5px" />
                    </div>
                  </a-form-item>
                </a-col>
                <a-col :md="4" :sm="24">
                  <span class="table-page-search-submitButtons" :style="{ float: 'right', overflow: 'hidden' }">
                    <a-button type="primary" @click="onSearch()">搜索</a-button>
                  </span>
                </a-col>
              </a-row>
              <a-row>
                <a-col>
                  <a-button type="primary" @click="$refs.addTable.visible = true">新增人员</a-button>
                </a-col>
              </a-row>
            </a-form>
          </div>
        </a-tab-pane>
        <a-tab-pane key="1" tab="角色管理" force-render>
          <div class="table-page-search-wrapper">
            <a-form layout="inline" @keyup.enter.native="onSearch()">
              <a-row :gutter="48">
                <a-col :md="6" :sm="24">
                  <a-form-item style="display: flex">
                    <div style="display: flex">
                      <a-select v-model="queryParamRole.searchRoleType" placeholder="请选择" style="width: 130px">
                        <a-select-option v-for="(item, index) in searchTypeList2" :key="index" :value="item.type">{{ item.name }}</a-select-option>
                      </a-select>
                      <a-input v-model="queryParamRole.searchValue" placeholder="请输入" style="margin-left: 5px" />
                    </div>
                  </a-form-item>
                </a-col>

                <a-col :md="4" :sm="24">
                  <span class="table-page-search-submitButtons" :style="{ float: 'right', overflow: 'hidden' }">
                    <a-button type="primary" @click="onSearch()" style="margin-right: 24px">搜索</a-button>
                  </span>
                </a-col>
                <a-col :md="24" :sm="24">
                  <div style="display: flex">
                    <a-button type="primary" @click="jump('add')">新增角色</a-button>
                  </div>
                </a-col>
              </a-row>
            </a-form>
          </div>
        </a-tab-pane>
      </a-tabs>
      <s-table ref="table" size="default" :rowKey="record => record.id" :columns="columns" :data="loadData" :pagination="pagination" :bordered="false" style="margin-top: 24px">
        <span slot="serial" slot-scope="text, record, index">
          {{ (pagination.current - 1) * pagination.pageSize + index + 1 }}
        </span>
        <span slot="themeRoleList" slot-scope="text, record">
          <a-tag style="margin: 2px" v-for="(item, index) in record.themeRoleList" :key="index">
            {{ item.name }}
          </a-tag>
        </span>
        <span slot="action" slot-scope="text, record">
          <template v-if="currentTab == 0">
            <a @click="editHandle(record)">编辑</a>
            <a-divider type="vertical" />
            <a-popconfirm ok-text="Yes" title="是否确认删除" cancel-text="No" @confirm="deleteUser(record.id)">
              <a>删除</a>
            </a-popconfirm>
          </template>
          <template v-else>
            <a @click="jump(record.id)">编辑</a>
            <a-divider type="vertical" />
            <a v-if="record.status == 'N'" @click="editRoleHandle(1,record.id)">启用</a>
            <a-divider type="vertical" />
            <a v-if="record.status == 'Y'" @click="editRoleHandle(0,record.id)">禁用</a>
            <a-divider type="vertical" v-if="record.status == 'N'"/>
            <a-popconfirm ok-text="Yes" title="是否确认删除" cancel-text="No" @confirm="editRoleHandle(2,record.id)" v-if="record.status == 'N'">
              <a>删除</a>
            </a-popconfirm>
          </template>
        </span>
      </s-table>
    </a-card>
    <add-table ref="addTable" @updataTable="updataTable"></add-table>
    <a-modal title="人员编辑" width="30vw" :visible="editVisible" @ok="handleEditOk" @cancel="editVisible = false">
      <a-descriptions>
        <a-descriptions-item label="姓名"> {{ editUserDetail.employeeName }} </a-descriptions-item>
        <a-descriptions-item label="账号"> {{ editUserDetail.account }} </a-descriptions-item>
      </a-descriptions>
      <a-descriptions>
        <a-descriptions-item label="工号"> {{ editUserDetail.workNo }} </a-descriptions-item>
        <a-descriptions-item label="手机号"> {{ editUserDetail.phone }} </a-descriptions-item>
      </a-descriptions>
      <div class="select-box">
        <span>角色：</span>
        <a-select v-model="themeRoleListIdArr" placeholder="多选" show-search style="width: 70%" mode="multiple">
          <a-select-option v-for="(item, index) in selectRoleList" :key="index" :value="item.id">{{ item.name }}</a-select-option>
        </a-select>
      </div>
    </a-modal>
  </div>
</template>
<script>
import { userList, roleList, editUserRole,roleEdit,deleteUserRole } from '@/api/pos/authority'
import { STable } from '@/views/box/components'
import addTable from '@/views/pos+/material/components/addUserModal'
const columns1 = [
  {
    title: '姓名',
    align: 'center',
    dataIndex: 'employeeName',
    scopedSlots: { customRender: 'employeeName' }
  },
  {
    title: '工号',
    align: 'center',
    dataIndex: 'workNo',
    scopedSlots: { customRender: 'workNo' }
  },
  {
    title: '账号',
    align: 'center',
    dataIndex: 'account',
    scopedSlots: { customRender: 'account' }
  },
  {
    title: '手机号',
    align: 'center',
    dataIndex: 'phone',
    scopedSlots: { customRender: 'phone' }
  },
  {
    title: '角色',
    align: 'center',
    dataIndex: 'themeRoleList',
    scopedSlots: { customRender: 'themeRoleList' }
  },
  {
    title: '操作',
    dataIndex: 'action',
    width: '120px',
    align: 'center',
    fixed: 'right',
    scopedSlots: { customRender: 'action' }
  }
]
const columns2 = [
  {
    title: 'ID',
    align: 'center',
    dataIndex: 'id'
  },
  {
    title: '角色名',
    align: 'center',
    dataIndex: 'name'
  },
  {
    title: '备注',
    align: 'center',
    dataIndex: 'remark'
  },
  {
    title: '操作',
    dataIndex: 'action',
    width: '240px',
    align: 'center',
    fixed: 'right',
    scopedSlots: { customRender: 'action' }
  }
]
export default {
  components: {
    STable,
    addTable
  },
  data() {
    return {
      defaultKey: localStorage.getItem('roleTab')?localStorage.getItem('roleTab'):0,
      columns1: columns1,
      columns2: columns2,
      columns: localStorage.getItem('roleTab')== 1?columns2:columns1,
      editVisible: false,
      editParam: {},
      currentTab: localStorage.getItem('roleTab')?localStorage.getItem('roleTab'):0,
      queryParamUser: {
        searchType:'workNo'
      },
      queryParamRole: {},
      condition: {},
      loadData: parameter => this.fetchData(parameter),
      pagination: {
        total: 0,
        showTotal: total => `共有 ${total} 条数据`
      },
      roleArr: [], // 人员编辑角色,
      selectRoleList: [], // 角色
      searchTypeList: [
        { type: 'employeeName', name: '姓名' },
        { type: 'workNo', name: '工号' },
        { type: 'phone', name: '手机号' }
      ],
      searchTypeList2: [
        { type: 'roleId', name: '角色ID' },
        { type: 'roleName', name: '角色名' },
      ],
      userParam: {},
      roleParam: {},
      editUserDetail: '',
      themeRoleListIdArr: []
    }
  },
  mounted() {
    // this.currentTab = localStorage.getItem("roleTab")?localStorage.getItem("roleTab"):0
    this.getCondition()
  },
  methods: {
    updataTable(){
      this.$refs.table.refresh()
    },
    // 新增人员刷新列表
    jump(id){
      this.$router.push(`/pos+/pos+manage/authority/editRole/${id}`)
    },
    tabChange(key) {
      this.currentTab = key
      if (this.currentTab == 0) {
        this.columns = this.columns1
      } else {
        this.columns = this.columns2
      }
      localStorage.setItem('roleTab',key)
      this.$refs.table.refresh()
    },
    // 删除人员
    async deleteUser(record) {
        const res = await deleteUserRole(record)
        if (res.code == 200) {
          this.$refs.table.refresh()
        } else {
          this.$message.error(res.msg || res.message)
        }
    },
    // 编辑角色
    async editRoleHandle(key,val){
      let param
      if(key == 0){
        // 禁用
        param = {
          roleId : val,
          status : 'N',
        }
      }else if(key == 1){
        // 启用
        param = {
          roleId : val,
          status : 'Y',
        }
      }else if(key == 2){
        // 删除
        param = {
          roleId : val,
          deleted : 1
        }
      }
      const res = await roleEdit(param)
      if(res.code == 200){
        this.$refs.table.refresh()
      }else{
        this.$message.error(res.msg || res.message)
      }
    },
    // 搜索
    onSearch() {
      let param = {}
      if (this.currentTab == 0) {
        // 人员搜索
        param = {
          roleList: this.queryParamUser.roleList
        }
        if (this.queryParamUser.searchType == 'employeeName') {
          Object.assign(param, {
            employeeName: this.queryParamUser.searchValue
          })
        } else if (this.queryParamUser.searchType == 'workNo') {
          Object.assign(param, {
            workNo: this.queryParamUser.searchValue
          })
        } else if (this.queryParamUser.searchType == 'phone') {
          Object.assign(param, {
            phone: this.queryParamUser.searchValue
          })
        }
        this.userParam = param
      } else {
        // 角色搜索
        if(this.queryParamRole.searchRoleType == 'roleId'){
          Object.assign(param, {
            roleId: this.queryParamRole.searchValue
          })
        }else{
          Object.assign(param, {
            roleName: this.queryParamRole.searchValue
          })
        }
        this.roleParam = param
      }
      this.$refs.table.refresh()
    },
    editHandle(record) {
      this.editVisible = true
      this.editUserDetail = record
      let idArr = []
      record.themeRoleList.map((item, index) => {
        idArr.push(item.id)
      })
      this.themeRoleListIdArr = idArr
    },
    // 修改员工角色
    async handleEditOk() {
      if(this.themeRoleListIdArr.length == 0){
        this.$toast('选择需要添加的角色')
        return
      }
      this.editVisible = false
      let list = []
      list = [{
        employeeId: this.editUserDetail.id,
        employeeName: this.editUserDetail.employeeName,
        phone: this.editUserDetail.phone,
        workNo: this.editUserDetail.workNo,
        account: this.editUserDetail.account
      }]
      const param = {
        employeeList : list,
        roleIds: this.themeRoleListIdArr.join(',')
      }
      const res = await editUserRole(param)
      if (res.code == 200) {
        this.$refs.table.refresh()
      } else {
        this.$message.error(res.msg || res.message)
      }
    },
    editChangeRole(value) {
      this.editParam.roleCode = value
    },
    // 获取条件
    getCondition() {
      let params = {
        current: 1,
        size: 100
      }
      roleList(params).then(res => {
        if (res.code == 200) {
          this.selectRoleList = res.data.records
        }
      })
    },
    async fetchData(parameter) {
      let queryParamUser = {}
      if (this.currentTab == 0) {
        queryParamUser = JSON.parse(JSON.stringify(this.userParam))
      } else {
        queryParamUser = JSON.parse(JSON.stringify(this.roleParam))
      }

      const data = {}
      data.userListQto = queryParamUser

      data.userListQto.current = parameter.pageNo
      data.userListQto.size = parameter.pageSize
      let res
      if (this.currentTab == 0) {
        res = await userList(data.userListQto)
      }else{
        res = await roleList(data.userListQto)
      }
      if (res.code === 200) {
          this.pagination.current = res.data.current
          const { total, size, current } = res.data
          const data = {
            page: {
              count: total,
              pageNo: current,
              pageSize: size,
              pages: Math.ceil(total / size)
            },
            data: res.data.records
          }
          return data
        } else {
          this.$message.error(res.msg || res.message)
          const data = {
            page: {
              pageNo: 0,
              count: 0,
              pageSize: 10
            },
            data: []
          }
          return data
        }
      // return userList(data.userListQto).then(res => {
        
      // })
    }
  }
}
</script>
<style lang="less" scoped>
.select-box {
  display: flex;
  margin: 30px 0;
}
</style>